from flask import Blueprint, jsonify, request
from app.models.Skillc2 import Book, BookReview, User
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

book_bp = Blueprint('book', __name__)

@book_bp.route('/books', methods=['GET'])
def get_books():
    """获取书籍列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        book_type = request.args.get('type')
        keyword = request.args.get('keyword')

        # 构建查询
        query = Book.query
        
        # 按类型筛选
        if book_type:
            query = query.filter(Book.Type == book_type)
            
        # 按关键词搜索
        if keyword:
            query = query.filter(
                db.or_(
                    Book.Title.like(f'%{keyword}%'),
                    Book.Author.like(f'%{keyword}%'),
                    Book.Content.like(f'%{keyword}%')
                )
            )

        # 分页
        pagination = query.paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [book.to_dict() for book in pagination.items],
                'total': pagination.total,
                'pages': pagination.pages,
                'current_page': page
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
    """获取单本书籍详情"""
    try:
        book = Book.query.get_or_404(book_id)
        return jsonify({
            'status': 'success',
            'data': book.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books', methods=['POST'])
@jwt_required()
def create_book():
    """创建新书籍"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        if 'title' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要字段: title'
            }), 400

        # 创建书籍
        book = Book(
            Title=data['title'],
            Author=data.get('author', '未知'),
            Type=data.get('type', '其他'),
            Price=float(data.get('price', 0.0)),
            Content=data.get('content', '暂无简介'),
            CoverImage=data.get('cover_image')
        )
        
        db.session.add(book)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '书籍创建成功',
            'data': book.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books/<int:book_id>', methods=['PUT'])
@jwt_required()
def update_book(book_id):
    """更新书籍信息"""
    try:
        book = Book.query.get_or_404(book_id)
        data = request.get_json()

        # 更新可修改的字段
        if 'title' in data:
            book.Title = data['title']
        if 'author' in data:
            book.Author = data['author']
        if 'type' in data:
            book.Type = data['type']
        if 'price' in data:
            book.Price = float(data['price'])
        if 'content' in data:
            book.Content = data['content']
        if 'cover_image' in data:
            book.CoverImage = data['cover_image']

        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '书籍信息更新成功',
            'data': book.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books/<int:book_id>', methods=['DELETE'])
@jwt_required()
def delete_book(book_id):
    """删除书籍"""
    try:
        book = Book.query.get_or_404(book_id)
        
        # 先删除相关的书评
        BookReview.query.filter_by(BookId=book_id).delete()
        
        # 再删除书籍
        db.session.delete(book)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '书籍删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books/<int:book_id>/reviews', methods=['GET'])
def get_book_reviews(book_id):
    """获取书籍评价列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        book = Book.query.get_or_404(book_id)
        reviews = book.reviews.filter_by(IsDeleted=False).paginate(page=page, per_page=per_page)

        return jsonify({
            'status': 'success',
            'data': {
                'items': [review.to_dict() for review in reviews.items],
                'total': reviews.total,
                'pages': reviews.pages,
                'current_page': page
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/books/<int:book_id>/reviews', methods=['POST'])
@jwt_required()
def create_review(book_id):
    """创建书籍评价"""
    try:
        data = request.get_json()
        user_id = int(get_jwt_identity())

        # 验证评价内容
        if not data or not data.get('content'):
            return jsonify({
                'status': 'error',
                'message': '评价内容不能为空'
            }), 400

        # 检查是否已经评价过
        existing_review = BookReview.query.filter_by(
            BookId=book_id,
            UserId=user_id,
            IsDeleted=False
        ).first()
        
        if existing_review:
            return jsonify({
                'status': 'error',
                'message': '您已经评价过这本书'
            }), 400

        # 创建评价
        review = BookReview(
            BookId=book_id,
            UserId=user_id,
            Content=data['content']
        )
        
        db.session.add(review)
        
        # 更新书籍评价数
        book = Book.query.get_or_404(book_id)
        if book:
            book.ReviewCount = BookReview.query.filter_by(BookId=book_id, IsDeleted=False).count() + 1
        
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '评价发布成功',
            'data': review.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/reviews/<int:review_id>', methods=['PUT'])
@jwt_required()
def update_review(review_id):
    """更新评价"""
    try:
        user_id = int(get_jwt_identity())
        review = BookReview.query.get_or_404(review_id)

        # 验证是否是评价作者
        if review.UserId != user_id:
            return jsonify({
                'status': 'error',
                'message': '只能修改自己的评价'
            }), 403

        data = request.get_json()
        
        # 验证评价内容
        if not data or not data.get('content'):
            return jsonify({
                'status': 'error',
                'message': '评价内容不能为空'
            }), 400

        # 更新评价内容
        review.Content = data['content']
        review.UpdateTime = datetime.now()
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '评价更新成功',
            'data': review.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/reviews/<int:review_id>', methods=['DELETE'])
@jwt_required()
def delete_review(review_id):
    """删除评价（软删除）"""
    try:
        user_id = int(get_jwt_identity())
        review = BookReview.query.get_or_404(review_id)

        # 验证是否是评价作者
        if review.UserId != user_id:
            return jsonify({
                'status': 'error',
                'message': '只能删除自己的评价'
            }), 403

        # 软删除评价
        review.IsDeleted = True
        review.UpdateTime = datetime.now()
        
        # 更新书籍评价数
        book = Book.query.get_or_404(review.BookId)
        book.ReviewCount = BookReview.query.filter_by(BookId=review.BookId, IsDeleted=False).count() - 1
        
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '评价删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@book_bp.route('/reviews/<int:review_id>/like', methods=['POST'])
@jwt_required()
def like_review(review_id):
    """点赞评价"""
    try:
        review = BookReview.query.get_or_404(review_id)
        review.LikeCount += 1
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '点赞成功',
            'data': {
                'like_count': review.LikeCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 